//
//  File.swift
//
//
//  Created by didi on 2022/9/13.
//

import Fluent
import Foundation
import MolecularObjects

public extension QueryBuilder where Model: MetadataRepresentable {
    func joinMetadata() -> QueryBuilder<Model> {
        join(SystemMetadataModel.self, on: \SystemMetadataModel.$reference == \Model._$id)
            .filter(SystemMetadataModel.self, \.$module == Model.From.uniqueKey)
            .filter(SystemMetadataModel.self, \.$model == Model.uniqueKey)
    }

    func joinVisibleMetadata() -> QueryBuilder<Model> {
        joinMetadata()
            .filterMetadataByVisibleStatus()
    }

    func joinPublicMetadata() -> QueryBuilder<Model> {
        joinMetadata()
            .filterMetadata(by: .published)
            .filterMetadata(by: Date())
    }

    func filterMetadata(by path: String) -> QueryBuilder<Model> {
        filter(SystemMetadataModel.self, \.$slug == path.trimmingSlashes())
    }

    func filterMetadata(by status: Metadata.Status) -> QueryBuilder<Model> {
        filter(SystemMetadataModel.self, \.$status == status)
    }

    func filterMetadataByVisibleStatus() -> QueryBuilder<Model> {
        filter(SystemMetadataModel.self, \.$status != .archived)
    }

    func filterMetadata(by date: Date) -> QueryBuilder<Model> {
        filter(SystemMetadataModel.self, \.$date <= date)
    }

    func sortMetadataByDate(_ direction: DatabaseQuery.Sort.Direction = .descending) -> QueryBuilder<Model> {
        sort(SystemMetadataModel.self, \.$date, direction)
    }
}
